package com.resou.reader.paycenter;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Paint;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.SpannableString;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.style.ForegroundColorSpan;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.resou.reader.R;
import com.resou.reader.api.entry.MultiConfigBean;
import com.resou.reader.base.v.BaseActivity;
import com.resou.reader.commom.Constant;
import com.resou.reader.mine.IView.UserInstance;
import com.resou.reader.mine.paycenter.PayCenterActivity;
import com.resou.reader.paycenter.p.BatchPayPresenter;
import com.resou.reader.paycenter.v.IBatchPayView;
import com.resou.reader.utils.log.DLog;
import com.resou.reader.view.Loading;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class BatchPayActivity extends BaseActivity<BatchPayPresenter> implements IBatchPayView {

    @BindView(R.id.recyclerView)
    RecyclerView mRecyclerView;
    @BindView(R.id.tvTitle)
    TextView tvTitle;
    /**
     * 展示书名
     */
    @BindView(R.id.book_name_text)
    TextView mBookNameTv;

    /**
     * 章节名称
     */
    @BindView(R.id.chapter_name_text)
    TextView mChapterNameTv;

    /**
     * 购买按钮
     */
    @BindView(R.id.pay_text)
    TextView mPayTv;

    /**
     * 余额文本
     */
    @BindView(R.id.balance_text)
    TextView mBalanceTv;

    /**
     * 显示实际费用的TextView
     */
    @BindView(R.id.reality_price_text)
    TextView mRealityPriceTv;

    @BindView(R.id.voucher_used)
    TextView mVoucherUsed;

    @BindView(R.id.voucher_used_group)
    FrameLayout mVoucherUsedGroup;
    int realPrice = 0;
    private Adapter mAdapter = new Adapter(R.layout.item_batch_pay);

    @Override
    public int getLayoutId() {
        return R.layout.activity_batch_pay;
    }

    @Override
    protected void initPresenter() {
        presenter = new BatchPayPresenter(this, getIntent().getStringExtra(Constant.EXTRA_BOOK_ID), getIntent().getStringExtra(Constant.EXTRA_CHAPTER_ID));
    }

    @Override
    protected void initView() {
        tvTitle.setText("购买章节");
        showLoading();
        mBookNameTv.setText(getIntent().getStringExtra(Constant.EXTRA_BOOK_NAME));
        mChapterNameTv.setText(String.valueOf("从 " + getIntent().getStringExtra(Constant.EXTRA_CHAPTER_NAME) + " 向后"));

        mRecyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        mRecyclerView.setAdapter(mAdapter);

        DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(this, LinearLayoutManager.VERTICAL);

        Drawable drawable = getResources().getDrawable(R.drawable.custom_divider_drawable);
        dividerItemDecoration.setDrawable(drawable);
        mRecyclerView.addItemDecoration(dividerItemDecoration);

        mAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                for (int i = 0, count = mRecyclerView.getChildCount(); i < count; i++) {
                    mRecyclerView.getChildAt(i).setSelected(false);
                }
                view.setSelected(true);
                int price = mAdapter.getData().get(position).getPayPrice();
                int voucherBalance = (int) UserInstance.getLoginData().getGiftBlance();
                if (UserInstance.getLoginData().getBlance() + voucherBalance < price) {
                    mPayTv.setText(R.string.please_pay_where_insufficient_balance);
                } else {
                    mPayTv.setText(R.string.purchase);
                }
                mPayTv.setTag(mAdapter.getData().get(position));

                // 计算已抵用热券
                int voucherUsed;
                if (voucherBalance == 0) {
                    mVoucherUsedGroup.setVisibility(View.GONE);
                    voucherUsed = 0;
                } else {
                    if (price > voucherBalance) {
                        voucherUsed = voucherBalance;
                    } else {
                        voucherUsed = price;
                    }
                    mVoucherUsedGroup.setVisibility(View.VISIBLE);
                    mVoucherUsed.setText(String.valueOf("已抵用" + voucherUsed + "热券"));
                }

                // 计算实际支付热币
                SpannableString ss = new SpannableString("实付：" + (price - voucherUsed) + "热币");
                ss.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.theme_color)), "实付：".length(), ss.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                mRealityPriceTv.setText(ss);
            }
        });
        initPayView();
    }

    @Override
    protected void retryRefreshData() {
        presenter.requestMultiConfig();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == Constant.PAY_REQUEST_CODE && resultCode == Activity.RESULT_OK) {
            initPayView();
            setResult(RESULT_OK);
        }
    }

    @Override
    public void initPayView() {
        int currencyBalance = (int) UserInstance.getLoginData().getBlance();
        int voucherBalance = (int) UserInstance.getLoginData().getGiftBlance();
        SpannableStringBuilder ssb = new SpannableStringBuilder();
        ssb.append(String.valueOf(getResources().getString(R.string.balance) + " "));

        ssb.append(String.valueOf(currencyBalance));
        ssb.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.theme_color)), ssb.length() - String.valueOf(currencyBalance).length(), ssb.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        ssb.append(getResources().getString(R.string.currency));

        ssb.append(String.valueOf(" + "));
        ssb.append(String.valueOf(voucherBalance));
        ssb.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.theme_color)), ssb.length() - String.valueOf(voucherBalance).length(), ssb.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        ssb.append(getResources().getString(R.string.voucher));
        mBalanceTv.setText(ssb);

        if (mPayTv.getTag() != null) {
            MultiConfigBean bean = (MultiConfigBean) mPayTv.getTag();
            if (UserInstance.getLoginData().getBlance() + UserInstance.getLoginData().getGiftBlance() < bean.getPayPrice()) {
                mPayTv.setText(R.string.please_pay_where_insufficient_balance);
            } else {
                mPayTv.setText(R.string.purchase);
            }
        }
    }

    @OnClick(R.id.pay_text)
    public void onClick(View v) {
        if (mPayTv.getTag() != null) {
            MultiConfigBean bean = (MultiConfigBean) mPayTv.getTag();
            if (UserInstance.getLoginData().getBlance() + UserInstance.getLoginData().getGiftBlance() < bean.getPayPrice()) {
                PayCenterActivity.start(this);
            } else {
//                Loading.getInstance().setLoadingText("付费中...");
//                Loading.getInstance().show(getSupportFragmentManager());
                showLoading();
                presenter.multiChapterPay(getIntent().getStringExtra(Constant.EXTRA_BOOK_NAME)
                        , getIntent().getStringExtra(Constant.EXTRA_CHAPTER_NAME)
                        , bean.getPayPrice(), bean.getMutiCode());
            }
        }
    }

    @Override
    public Context getViewContext() {
        return this;
    }

    /**
     * @param activity    Resource Activity
     * @param bookId      书唯一标识
     * @param bookName    书名
     * @param chapterId   章节ID
     * @param chapterName 章节名称
     */
    public static void startActivityForResult(Activity activity, String bookId, String bookName, String chapterId, String chapterName, int requestCode) {
        Intent intent = new Intent(activity, BatchPayActivity.class);
        intent.putExtra(Constant.EXTRA_BOOK_ID, bookId);
        intent.putExtra(Constant.EXTRA_BOOK_NAME, bookName);
        intent.putExtra(Constant.EXTRA_CHAPTER_ID, chapterId);
        intent.putExtra(Constant.EXTRA_CHAPTER_NAME, chapterName);

        activity.startActivityForResult(intent, requestCode);
    }

    @Override
    public void onRequestConfigSuccessfully(List<MultiConfigBean> configBeans) {
//        Loading.getInstance().dismiss();
        dissLoading();
        mAdapter.addData(configBeans);
        mAdapter.notifyDataSetChanged();
    }

    @Override
    public void onRequestConfigError() {
//        Loading.getInstance().dismiss();
        dismissNetErrorView();
        showNetErrorView(R.id.rlContent);
    }

    @Override
    public void multiChapterPaySuccess(String chapterId, int payType) {
        //购买成功了，返回到ReaderActivity的时候需要鉴权
        Intent data = new Intent();
        data.putExtra(Constant.EXTRA_CHAPTER_ID, chapterId);
        data.putExtra(Constant.EXTRA_PAY_TYPE, payType);
        setResult(RESULT_OK, data);
//        Loading.getInstance().dismiss();
        dissLoading();
        finish();
    }

    @OnClick(R.id.ivBack)
    public void onClick() {
        finish();
    }

    private class Adapter extends BaseQuickAdapter<MultiConfigBean, BaseViewHolder> {

        public Adapter(int layoutResId) {
            super(layoutResId);
        }

        @Override
        protected void convert(BaseViewHolder helper, MultiConfigBean item) {
//            ((TextView) helper.getView(R.id.sale_price_text)).getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);


            if (1 == UserInstance.getLoginData().getIsVipUser()) {
                helper.setText(R.id.tvChapterName, item.getMutiType())
                        .setText(R.id.tvDisCountDes, item.getVipDiscountDesc() + "")
                        .setText(R.id.tvRBPrice, String.valueOf(item.getPayPrice() + " " + getResources().getString(R.string.currency)))
                        .setText(R.id.tvYPrice, String.valueOf("   原：" + item.getOriginalPrice()) + " 热币   ")
                        .setText(R.id.tvDisCount, "   " + item.getDiscountDesc() + "   ");
                helper.getView(R.id.tvDisCountDes).setVisibility(View.VISIBLE);
                helper.getView(R.id.discount_text).setVisibility(View.GONE);
                helper.getView(R.id.tvDisCount).setVisibility(View.VISIBLE);
                helper.getView(R.id.tvYH).setVisibility(View.GONE);
                setLine(helper.getView(R.id.tvYPrice));
                setLine(helper.getView(R.id.tvDisCount));
            } else {
                helper.getView(R.id.tvDisCountDes).setVisibility(View.GONE);
                helper.getView(R.id.discount_text).setVisibility(View.VISIBLE);
                helper.getView(R.id.tvDisCount).setVisibility(View.GONE);
                helper.getView(R.id.tvYH).setVisibility(View.VISIBLE);
                helper.setText(R.id.tvChapterName, item.getMutiType())
                        .setText(R.id.discount_text, item.getVipDiscountDesc() + "")
                        .setText(R.id.tvRBPrice, String.valueOf(item.getOriginalPrice() - item.getPayPrice() + " " + getResources().getString(R.string.currency)))
                        .setText(R.id.tvYPrice, String.valueOf("原价：" + item.getOriginalPrice()) + " " + getResources().getString(R.string.currency));
            }

            if (helper.getLayoutPosition() == 0 && mPayTv.getTag() == null && mAdapter.getOnItemClickListener() != null) {
                mAdapter.getOnItemClickListener().onItemClick(mAdapter, helper.itemView, 0);
            }
        }
    }

    /**
     * 设置删除线
     *
     * @param tv_text
     */
    private void setLine(TextView tv_text) {
        tv_text.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG); //删除线
        tv_text.getPaint().setAntiAlias(true);// 抗锯齿
    }
}
